package com.hubu.web;

import com.hubu.mapper.administratorUserMapper;
import com.hubu.pojo.student_Information;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

@WebServlet("/updateStudent")
public class updateStudent extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if(request.getMethod().equals("POST")) {
            String id=request.getParameter("id");
            String name = request.getParameter("name");
            String gender = request.getParameter("gender");
            int age = Integer.parseInt(request.getParameter("age"));
            int credit = Integer.parseInt(request.getParameter("credit"));
            String classId = request.getParameter("classId");

            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            SqlSession sqlSession = sqlSessionFactory.openSession();

            student_Information student=new student_Information();
            student.setId(id);
            student.setName(name);
            student.setGender(gender);
            student.setAge(age);
            student.setCredit(credit);
            student.setClass_id(classId);

            administratorUserMapper administratorUserMapper=sqlSession.getMapper(com.hubu.mapper.administratorUserMapper.class);
            administratorUserMapper.updateByStudentId(student);
            sqlSession.commit();
            sqlSession.close();
            writer.println("<script type='text/javascript'>");
            writer.println("alert('修改成功！');");
            writer.println("window.location='" + request.getContextPath() + "/adminHome';");
            writer.println("</script>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
